<template>
  <div>
    <!--面包屑组件-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片-->
    <el-card class="box-card">
      <!--提示信息-->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false"
                type="warning" show-icon></el-alert>
      <!--选择商品分类-->
      <el-row :gutter="20">
        <el-col>
          <span>选择商品分类：</span>
          <!--级联选择框-->
          <el-cascader
          v-model="selectId"
          :options="goodsParamsList"
          :props="{ ...propsConfig }"
          @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!--标签页-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!--添加动态参数-->
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible">动态参数</el-button>
          <!--表格-->
          <el-table :data="manyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <el-tag closable
                            v-for="item in props.row.attr_vals" :key="item"
                            :disable-transitions="false"
                            @close="handleClose(props.row, item)">
                      {{item}}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="props.row.inputVisible"
                      v-model="props.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(props.row)"
                      @blur="handleInputConfirm(props.row)">
                    </el-input>
                    <el-button v-else class="button-new-tag"
                               size="small" @click="showInput(props.row)">+ New Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="props">
                <el-button size="mini" type="primary" class="el-icon-edit" @click="editParams(props.row)">修改</el-button>
                <el-button size="mini" type="danger" class="el-icon-delete" @click="deleteParams(props.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--添加静态属性-->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible">静态属性</el-button>
          <!--表格-->
          <el-table :data="onlyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item>
                    <el-tag closable
                            v-for="item in props.row.attr_vals" :key="item"
                            :disable-transitions="false"
                            @close="handleClose(props.row, item)">
                      {{item}}
                    </el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="props.row.inputVisible"
                      v-model="props.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(props.row)"
                      @blur="handleInputConfirm(props.row)">
                    </el-input>
                    <el-button v-else class="button-new-tag"
                               size="small" @click="showInput(props.row)">+ New Tag</el-button>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="操作名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="props">
                <el-button size="mini" type="primary" class="el-icon-edit" @click="editParams(props.row)">修改</el-button>
                <el-button size="mini" type="danger" class="el-icon-delete" @click="deleteParams(props.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!---->
    <!---->
    <!---->
    <!--添加动态参数或静态属性-->
    <el-dialog :title="activeName==='many'?'添加动态参数':'添加静态属性'"
      :visible.sync="addDialog"
      width="50%" @close="addDialogVisibleClose">
      <!--form表单-->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialog = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!---->
    <!---->
    <!---->
    <!--修改动态参数或静态属性-->
    <el-dialog :title="activeName==='many'?'修改动态参数':'修改静态属性'"
               :visible.sync="editDialog"
               width="50%" @close="editDialogVisibleClose">
      <!--form表单-->
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="editPutParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      // 商品分类列表
      goodsParamsList: [],
      // 选择的商品的id
      selectId: [],
      // 选择商品的级联选择框配置
      propsConfig: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 标签页
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 监听添加点击事件
      addDialog: false,
      // 添加表单
      addForm: {
        attr_name: ''
      },
      addRules: {
        attr_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      // 监听编辑点击事件
      editDialog: false,
      editForm: {
        attr_name: ''
      },
      // 编辑规则
      editRules: {
        attr_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      // 待编辑的数据
      editInfo: {
        attr_name: ''
      }
    }
  },
  created: function() {
    this.getCategories()
  },
  methods: {
    getCategories: async function() {
      var { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.goodsParamsList = res.data
    },
    // 级联选择框选择的商品分类
    handleChange: function () {
      this.getParamsData()
    },
    // 标签页点击事件
    handleTabClick: function () {
      this.getParamsData()
    },
    // 获取参数列表
    getParamsData: async function () {
      if (this.selectId.length !== 3) {
        this.selectId = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      var { data: res } = await this.$http.get(`categories/${this.cateId()}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败！')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 当前选中的三级分类的id
    cateId: function () {
      if (this.selectId.length !== 3) {
        return null
      }
      return this.selectId[2]
    },
    // 添加动态参数
    addDialogVisible: function () {
      this.addDialog = true
    },
    // 监听添加对话框的关闭事件
    addDialogVisibleClose: function () {
      this.$refs.addFormRef.resetFields()
    },
    // 确定添加动态参数或静态属性
    addParams: function () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        var { data: res } = await this.$http.post(`categories/${this.selectId[2]}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加数据失败')
        }
        this.addDialog = false
        this.getParamsData()
      })
    },
    // 修改动态参数或静态属性
    editParams: function (row) {
      this.editDialog = true
      this.editForm.attr_name = row.attr_name
      this.editInfo = row
    },
    // 关闭编辑对话框，重置表单
    editDialogVisibleClose: function () {
      this.$refs.editFormRef.resetFields()
      this.editDialog = false
    },
    // 提交修改动态参数或静态属性表单
    editPutParams: function () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        var { data: res } = await this.$http.put(`categories/${this.editInfo.cat_id}/attributes/${this.editInfo.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.editInfo.attr_sel
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败！')
        }
        this.$message.success('修改成功！')
        this.editInfo.attr_name = this.editForm.attr_name
        this.editDialog = false
      })
    },
    // 删除参数
    deleteParams: function (row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败！')
        }
        this.getParamsData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点击关闭，删除参数
    handleClose: async function (row, item) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
      var { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑提交参数失败')
      }
      this.$message.success('编辑提交参数成功')
    },
    showInput: function (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 参数标签失去焦点时执行
    handleInputConfirm: async function (row) {
      // 如果输入的是空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      var { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑提交参数失败')
      }
      this.$message.success('编辑提交参数成功')
      // 将标签隐藏
      row.inputVisible = false
    }
  },
  computed: {
    isBtnDisabled: function () {
      return this.selectId.length !== 3
    }
  }
}
</script>

<style lang="less" scoped>
  .el-alert{
    margin-bottom: 15px;
  }
  .el-menu{
    margin-bottom: 15px;
  }
  .el-tag{
    margin-right: 15px;
  }
</style>
